package com.canace.novel.manager.redis;

import com.canace.novel.core.util.ImgVerifyCodeUtils;
import com.canace.novel.core.constant.CacheConsts;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.Duration;
import java.util.Objects;

/**
 * @author canace
 * @version 1.0
 * @description 验证码管理类
 * @date 2024/1/20 11:10
 */

@Component
@RequiredArgsConstructor
public class VerifyCodeManager {

    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 生成验证码，并返回base64图片
     *
     * @param sessionId 缓存字段
     * @return 验证码图片
     * @throws IOException 生成图片异常
     */
    public String getVerifyCode(String sessionId) throws IOException {
        // 创建4位长度的验证码
        String randomVerifyCode = ImgVerifyCodeUtils.getRandomVerifyCode(4);
        // 保存到redis中
        stringRedisTemplate.opsForValue().set(CacheConsts.IMG_VERIFY_CODE_CACHE_KEY + sessionId, randomVerifyCode, Duration.ofMinutes(5));
        // 返回验证码图片
        return ImgVerifyCodeUtils.genVerifyCodeImg(randomVerifyCode);
    }

    /**
     * 校验图形验证码
     */
    public boolean imgVerifyCodeOk(String sessionId, String verifyCode) {
        return Objects.equals(stringRedisTemplate.opsForValue()
                .get(CacheConsts.IMG_VERIFY_CODE_CACHE_KEY + sessionId), verifyCode);
    }

    /**
     * 从 Redis 中删除验证码
     */
    public void removeImgVerifyCode(String sessionId) {
        stringRedisTemplate.delete(CacheConsts.IMG_VERIFY_CODE_CACHE_KEY + sessionId);
    }
}
